<!-- stories/templates/stories/story_detail.html -->
{% extends 'stories/base.html' %}
{% load static %}

{% block title %}{{ story.title }} - AI故事生成网站{% endblock %}

{% block content %}
<div class="container">
    <div class="story-detail">
        <!-- 故事封面和标题 -->
        <div class="story-header">
            <div class="story-cover">
                {% if story.cover_image %}
                    <img src="{{ story.cover_image.url }}" alt="{{ story.title }}">
                {% else %}
                    <div class="cover-text">{{ story.title }}</div>
                {% endif %}
            </div>
            <div class="story-title-section">
                <h1>{{ story.title }}</h1>
                <div class="story-meta">
                    <span class="author">作者: <strong>{{ story.author.username }}</strong></span>
                    <span class="category">分类: <strong>{{ story.category.name }}</strong></span>
                    <span class="date">发布于: <strong>{{ story.created_at|date:"Y-m-d H:i" }}</strong></span>
                    <span class="views">👁️ {{ story.view_count }}次浏览</span>
                </div>

                <!-- 评分系统 -->
                <div class="story-rating">
                    <div class="rating-display">
                        <span class="rating-stars">
                            {% for i in "12345" %}
                                {% if forloop.counter <= story.average_rating|floatformat:"0"|add:"0" %}
                                    ★
                                {% else %}
                                    ☆
                                {% endif %}
                            {% endfor %}
                        </span>
                        <span class="rating-average">{{ story.average_rating|floatformat:1 }}/5.0</span>
                        <span class="rating-count">({{ story.rating_count }}人评分)</span>
                    </div>

                    {% if user.is_authenticated %}
                        {% if story.author != user %}
                            <div class="rating-form">
                                <form id="ratingForm">
                                    <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
                                    <label>您的评分:</label>
                                    <div class="star-input">
                                        {% for i in "12345" %}
                                            <input type="radio" id="star{{ forloop.counter }}" name="score" value="{{ forloop.counter }}"
                                                   {% if user_rating and user_rating.score == forloop.counter %}checked{% endif %}>
                                            <label for="star{{ forloop.counter }}" class="star-label" data-value="{{ forloop.counter }}">★</label>
                                        {% endfor %}
                                    </div>
                                    <button type="button" id="submitRating" class="btn btn-sm btn-rating">提交评分</button>
                                </form>
                            </div>
                        {% else %}
                            <div class="rating-login-prompt">
                                <p>您不能给自己的文章评分</p>
                            </div>
                        {% endif %}
                    {% else %}
                        <div class="rating-login-prompt">
                            <p>登录后可以评分</p>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>

        <!-- 故事内容 -->
        <div class="story-content">
            {{ story.content|linebreaks }}
        </div>

        <!-- 作者操作按钮 -->
        {% if user.is_authenticated and story.author == user %}
            <div class="author-actions">
                {% if story.status == 'pending' %}
                    <!-- 审核中状态，禁用编辑按钮并显示提醒 -->
                    <button class="btn btn-edit" disabled title="故事正在审核中，无法编辑">编辑故事</button>
                    <div class="status-pending-inline">故事正在审核中，无法编辑</div>
                {% else %}
                    <!-- 非审核中状态 -->
                    <a href="{% url 'stories:edit_story' story.id %}" class="btn btn-edit">编辑故事</a>
                    {% if story.status == 'draft' or story.status == 'rejected' %}
                        <form method="post" style="display: inline;">
                            {% csrf_token %}
                            <input type="hidden" name="status" value="pending">
                            <button type="submit" class="btn btn-publish" onclick="return confirm('确定要提交审核吗？')">提交审核</button>
                        </form>
                    {% endif %}
                {% endif %}
            </div>
        {% endif %}

        <!-- 评论区域 -->
        <div class="comments-section">
            <h2>读者评论 ({{ comments.count }})</h2>

            {% if user.is_authenticated %}
                <div class="comment-form">
                    <h3>发表评论</h3>
                    <form id="commentForm">
                        <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
                        <textarea name="content" placeholder="分享您的想法..." required></textarea>
                        <button type="submit" class="btn btn-primary">发表评论</button>
                    </form>
                </div>
            {% else %}
                <div class="login-prompt">
                    <p>登录后可以发表评论 <a href="{% url 'stories:login' %}">立即登录</a></p>
                </div>
            {% endif %}

            <div class="comments-list">
                {% for comment in comments %}
                    <div class="comment-item" data-comment-id="{{ comment.id }}">
                        <div class="comment-header">
                            <div class="comment-author">
                                <strong>{{ comment.author.username }}</strong>
                                <span class="comment-date">{{ comment.created_at|date:"Y-m-d H:i" }}</span>
                            </div>
                            {% if user.is_authenticated and comment.author == user %}
                                <button class="btn-delete-comment" data-comment-id="{{ comment.id }}">删除</button>
                            {% endif %}
                        </div>
                        <div class="comment-body">
                            <p>{{ comment.content }}</p>
                        </div>

                        <!-- 回复功能 -->
                        {% if user.is_authenticated %}
                            <div class="reply-section">
                                <button class="btn-reply">回复</button>
                                <div class="reply-form" style="display: none;">
                                    <form class="replyForm">
                                        <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
                                        <input type="hidden" name="parent_id" value="{{ comment.id }}">
                                        <textarea name="content" placeholder="回复 {{ comment.author.username }}..." required></textarea>
                                        <button type="submit" class="btn btn-sm btn-primary">提交回复</button>
                                        <button type="button" class="btn btn-sm btn-cancel">取消</button>
                                    </form>
                                </div>
                            </div>
                        {% endif %}

                        <!-- 回复列表 -->
                        {% if comment.replies.exists %}
                            <div class="replies-list">
                                {% for reply in comment.replies.all %}
                                    <div class="reply-item" data-comment-id="{{ reply.id }}">
                                        <div class="comment-header">
                                            <div class="comment-author">
                                                <strong>{{ reply.author.username }}</strong>
                                                <span class="comment-date">{{ reply.created_at|date:"Y-m-d H:i" }}</span>
                                                <span class="reply-to">回复 @{{ comment.author.username }}</span>
                                            </div>
                                            {% if user.is_authenticated and reply.author == user %}
                                                <button class="btn-delete-comment" data-comment-id="{{ reply.id }}">删除</button>
                                            {% endif %}
                                        </div>
                                        <div class="comment-body">
                                            <p>{{ reply.content }}</p>
                                        </div>
                                    </div>
                                {% endfor %}
                            </div>
                        {% endif %}
                    </div>
                {% empty %}
                    <div class="no-comments">暂无评论，快来抢沙发吧！</div>
                {% endfor %}
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    // 星星悬停和点击效果
    $('.star-input .star-label').hover(
        function() {
            // 鼠标悬停时点亮当前及之前的星星
            var value = $(this).data('value');
            $(this).parent().find('.star-label').each(function() {
                if ($(this).data('value') <= value) {
                    $(this).addClass('active');
                } else {
                    $(this).removeClass('active');
                }
            });
        },
        function() {
            // 鼠标离开时恢复原始状态（只保留选中的）
            $(this).parent().find('.star-label').removeClass('active');
            var checkedValue = $(this).parent().find('input[name="score"]:checked').val();
            if (checkedValue) {
                $(this).parent().find('.star-label').each(function() {
                    if ($(this).data('value') <= checkedValue) {
                        $(this).addClass('active');
                    }
                });
            }
        }
    );
    
    // 点击星星时选中并点亮
    $('.star-input .star-label').click(function() {
        var value = $(this).data('value');
        $(this).parent().find('input[name="score"]').prop('checked', false);
        $(this).parent().find('input[name="score"][value="' + value + '"]').prop('checked', true);
        
        // 点亮当前及之前的星星
        $(this).parent().find('.star-label').each(function() {
            if ($(this).data('value') <= value) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }
        });
    });
    
    // 初始化已选中的星星
    var checkedValue = $('.star-input input[name="score"]:checked').val();
    if (checkedValue) {
        $('.star-input .star-label').each(function() {
            if ($(this).data('value') <= checkedValue) {
                $(this).addClass('active');
            }
        });
    }

    // 评分功能
    $('#submitRating').click(function() {
        var score = $('input[name="score"]:checked').val();
        if (!score) {
            alert('请选择评分');
            return;
        }

        $.ajax({
            url: '{% url "stories:rate_story" story.id %}',
            type: 'POST',
            data: {
                'score': score,
                'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val()
            },
            success: function(response) {
                if (response.success) {
                    // 更新页面上的评分显示
                    $('.rating-stars').html('');
                    var fullStars = Math.round(response.average_rating);
                    for (var i = 1; i <= 5; i++) {
                        if (i <= fullStars) {
                            $('.rating-stars').append('★');
                        } else {
                            $('.rating-stars').append('☆');
                        }
                    }
                    $('.rating-average').text(parseFloat(response.average_rating).toFixed(1) + '/5.0');
                    $('.rating-count').text('(' + response.rating_count + '人评分)');
                    alert('评分成功！');
                }
            },
            error: function(xhr, status, error) {
                alert('评分失败：' + xhr.responseJSON.error);
            }
        });
    });

    // 评论功能
    $('#commentForm').submit(function(e) {
        e.preventDefault();
        var content = $('textarea[name="content"]').val().trim();

        if (!content) {
            alert('评论内容不能为空');
            return;
        }

        $.ajax({
            url: '{% url "stories:add_comment" story.id %}',
            type: 'POST',
            data: {
                'content': content,
                'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val()
            },
            success: function(response) {
                if (response.success) {
                    // 创建新的评论元素
                    var commentHtml = `
                        <div class="comment-item" data-comment-id="${response.comment.id}">
                            <div class="comment-header">
                                <div class="comment-author">
                                    <strong>${response.comment.author}</strong>
                                    <span class="comment-date">${response.comment.created_at}</span>
                                </div>
                                <button class="btn-delete-comment" data-comment-id="${response.comment.id}">删除</button>
                            </div>
                            <div class="comment-body">
                                <p>${response.comment.content}</p>
                            </div>
                            <div class="reply-section">
                                <button class="btn-reply">回复</button>
                                <div class="reply-form" style="display: none;">
                                    <form class="replyForm">
                                        <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
                                        <input type="hidden" name="parent_id" value="${response.comment.id}">
                                        <textarea name="content" placeholder="回复 ${response.comment.author}..." required></textarea>
                                        <button type="submit" class="btn btn-sm btn-primary">提交回复</button>
                                        <button type="button" class="btn btn-sm btn-cancel">取消</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    `;

                    // 添加到评论列表顶部
                    $('.comments-list').prepend(commentHtml);
                    $('textarea[name="content"]').val('');

                    // 重新绑定事件
                    bindCommentEvents();
                }
            },
            error: function(xhr, status, error) {
                alert('评论失败：' + xhr.responseJSON.error);
            }
        });
    });

    // 绑定评论相关事件
    function bindCommentEvents() {
        // 回复按钮
        $('.btn-reply').off('click').on('click', function() {
            $(this).next('.reply-form').slideToggle();
        });

        // 取消回复
        $('.btn-cancel').off('click').on('click', function() {
            $(this).closest('.reply-form').slideUp();
        });

        // 回复表单提交
        $('.replyForm').off('submit').on('submit', function(e) {
            e.preventDefault();
            var form = $(this);
            var content = form.find('textarea[name="content"]').val().trim();
            var parent_id = form.find('input[name="parent_id"]').val();

            if (!content) {
                alert('回复内容不能为空');
                return;
            }

            $.ajax({
                url: '{% url "stories:add_comment" story.id %}',
                type: 'POST',
                data: {
                    'content': content,
                    'parent_id': parent_id,
                    'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val()
                },
                success: function(response) {
                    if (response.success) {
                        // 创建新的回复元素
                        var replyHtml = `
                            <div class="reply-item" data-comment-id="${response.comment.id}">
                                <div class="comment-header">
                                    <div class="comment-author">
                                        <strong>${response.comment.author}</strong>
                                        <span class="comment-date">${response.comment.created_at}</span>
                                        <span class="reply-to">回复 @${$('.comment-item[data-comment-id="' + parent_id + '"] .comment-author strong').text()}</span>
                                    </div>
                                    <button class="btn-delete-comment" data-comment-id="${response.comment.id}">删除</button>
                                </div>
                                <div class="comment-body">
                                    <p>${response.comment.content}</p>
                                </div>
                            </div>
                        `;

                        // 找到对应的评论，添加回复
                        var repliesList = $('.comment-item[data-comment-id="' + parent_id + '"] .replies-list');
                        if (repliesList.length === 0) {
                            $('.comment-item[data-comment-id="' + parent_id + '"]').append('<div class="replies-list"></div>');
                            repliesList = $('.comment-item[data-comment-id="' + parent_id + '"] .replies-list');
                        }
                        repliesList.append(replyHtml);

                        // 清空表单并隐藏
                        form.find('textarea').val('');
                        form.slideUp();

                        // 重新绑定事件
                        bindCommentEvents();
                    }
                },
                error: function(xhr, status, error) {
                    alert('回复失败：' + xhr.responseJSON.error);
                }
            });
        });

        // 删除评论
        $('.btn-delete-comment').off('click').on('click', function() {
            if (!confirm('确定要删除这条评论吗？')) {
                return;
            }

            var commentId = $(this).data('comment-id');

            $.ajax({
                url: '/ajax/delete-comment/' + commentId + '/',
                type: 'POST',
                data: {
                    'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val()
                },
                success: function(response) {
                    if (response.success) {
                        $('.comment-item[data-comment-id="' + commentId + '"], .reply-item[data-comment-id="' + commentId + '"]').fadeOut(function() {
                            $(this).remove();
                        });
                    }
                },
                error: function(xhr, status, error) {
                    alert('删除失败：' + xhr.responseJSON.error);
                }
            });
        });
    }

    // 初始化事件绑定
    bindCommentEvents();
});
</script>
{% endblock %}